﻿(function () {
    const CREATE = 0;
    const MODEL = 1;
    const GLOBLE_KEY = "sys_config_cache";
    const CACHE_FLAG = "flag";
    const MAIN_PANEL = "main-panel";
    const CACHE_DAYS = 90;


    window.Config = {
        key: 'CachedKey',
        dbTypes: { 0: "SqlServer", 1: "MySql", 2: "Sqlite", 3: "PostgreSQL" },
        model: {},
        create: {},
        changeCallback: {},
        load: function (type, selector, successCallback, notExistsCallback) {
            loadCache();
            var html = '<option value="">请选择缓存的配置</option>';
            var model = type === CREATE ? this.create : this.model;
            var size = 0;
            for (var key in model) {
                html += '<option value="' + key + '">' + key + '</option>';
                ++size;
            }
            var cache = $('select[name=' + this.key + ']');
            cache.attr(CACHE_FLAG, type);
            cache.attr(MAIN_PANEL, selector);
            cache.html(html);
            if (size === 0) {
                notExistsCallback();
            } else {
                if (undefined !== successCallback) {
                    successCallback(model);
                }
            }
            if (undefined !== successCallback) {
                this.changeCallback[type] = successCallback;
            }
        },
        save: function (type, selector,funcKey) {
            var obj = $.serializeObj(selector);
            delete obj[this.key];
            var key = funcKey(obj);
            loadCache();
            if (type === CREATE) {
                this.create[key] = obj;
            } else {
                this.model[key] = obj;
            }
            saveCache();
            this.load(type, selector);
        }
};
    var CacheData = {
        model: {},
        create: {}
    };

    function loadCache() {
        var json = Cookies.get(GLOBLE_KEY);
        if (json === undefined) {
            return;
        }
        var data = JSON.parse(json);
        Config.model = data.model;
        Config.create = data.create;
    }

    function saveCache() {
        CacheData.model = Config.model;
        CacheData.create = Config.create;
        var value = JSON.stringify(CacheData);
        Cookies.set(GLOBLE_KEY, value, { expires: CACHE_DAYS, path: '/' });
    }

    $('select[name=' + Config.key + ']').on('change', e => {
        var target = $(e.target);
        var key = target.val();
        if (key === undefined) {
            return;
        }
        var flag = parseInt(target.attr(CACHE_FLAG));
        var panel = target.attr(MAIN_PANEL);
        var model = flag === CREATE ? Config.create : Config.model;
        var data = model[key];
        if (data === undefined) {
            return;
        }
        console.log(data);
        $.showTableObj(panel, data);
        var callback = Config.changeCallback[flag];
        console.log(callback);
        if (callback !== undefined) {
            callback(data);
        }
    });
})();